package com.rmb.util;
import com.rmb.entity.SourceEntity;

import java.sql.*;

/**
 * @Author ZhaoMuYang
 * @Date 2021/1/6 23:53
 */
public class JdbcUtil {

    private static final String MYSQL_DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String MYSQL_PRE = "jdbc:mysql://";
    private static final String MYSQL_SUFFIX="?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai";

    private static final String ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String SQLSERVER_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

    public static Boolean getConnection(SourceEntity source) {
        String url =MYSQL_PRE+source.getHost()+":"+source.getPort()+"/"+source.getDatabaseName()+MYSQL_SUFFIX;
        String username =source.getUsername();
        String password =source.getPassword();


        String sql="select @@version as version";

        Connection connection=null;
        PreparedStatement pstmt = null;
        ResultSet resultSet=null;

        try{//加载MySql的驱动类
            Class.forName(MYSQL_DRIVER) ;
        }catch(ClassNotFoundException e){
            System.out.println("找不到驱动程序类 ，加载驱动失败！");
            e.printStackTrace() ;
        }
        try{
            connection= DriverManager.getConnection(url , username , password ) ;
        }catch(SQLException se){
            System.out.println("数据库连接失败！");
            se.printStackTrace() ;
        }

        try {
            pstmt = connection.prepareStatement(sql);
            resultSet= pstmt.executeQuery();
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }

        System.out.println(ORACLE_DRIVER);
        System.out.println(SQLSERVER_DRIVER);
        if (resultSet==null){
            return false;
        }
        // 关闭记录集
        if(resultSet !=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        // 关闭声明
        if(pstmt !=null){
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // 关闭连接对象
        if(connection !=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

}
